import 'whatwg-fetch'
import { genParamStr } from './tools'
import localStore from 'store'

const defaultConfig = {
  method: 'GET',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': localStore.get('auth') && localStore.get('auth').token
  },
  mode: 'cors',
  cache: 'default'
}
function parseJSON (response) {
  return response.json()
}

function checkStatus (response) {
  if (response.status === 201 || response.status === 204) {
    return response
  }
  if (response.status >= 200 && response.status < 300) {
    return parseJSON(response)
  }

  const error = new Error(response.statusText)
  error.response = response
  throw error
}
function refreshToken () {
  return fetch('http://192.168.80.125/api/auth', Object.assign({},
    defaultConfig, {
      method: 'PUT',
      headers: {
        'Authorization': 'Bearer ' + localStore.get('auth').token
      }
    }))
    .then(checkStatus)
    .then(({ data }) => {
      localStore.set('auth', data)
    })
}
window.refreshToken = refreshToken
function checkToken () {
  const auth = localStore.get('auth')
  if (auth) {
    try {
      const expireTime = new Date(auth.expire_time * 1000).getTime() - Date.now()
      if (expireTime < 3600 * 1000 && expireTime > 0) refreshToken()
    } catch (err) {
      console.error(err)
    }
  }
}

function request (url, options) {
  checkToken()
  return fetch(url, options)
    .then(checkStatus)
}
export function get (url, params) {
  if (typeof params === 'undefined') {
    return request(url)
  }
  let paramStr
  if (typeof params === 'object') {
    paramStr = genParamStr(params)
  } else {
    paramStr = params
  }
  return request(`${url}?${paramStr}`, defaultConfig)
}
export function post (url, body, config) {
  const _config = Object.assign({}, defaultConfig, {
    method: 'POST',
    body: genParamStr(body)
  }, config)
  return request(url, _config)
}

export default {
  get,
  post,
  request
}
